package org.ourgrid.worker.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.interfaces.to.WorkerStatus;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.common.internal.response.OperationSucceedResponseTO;
import org.ourgrid.worker.business.controller.ExecutionController;
import org.ourgrid.worker.business.dao.WorkerDAOFactory;
import org.ourgrid.worker.business.messages.ControlMessages;
import org.ourgrid.worker.request.ResumeWorkerRequestTO;

public class ResumeWorkerRequester implements RequesterIF<ResumeWorkerRequestTO> {

	public List<IResponseTO> execute(ResumeWorkerRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();

		if (!request.canComponentBeUsed()) {
			OperationSucceedResponseTO to = new OperationSucceedResponseTO();
			to.setClientAddress(request.getClientAddress());
			to.setErrorCause(request.getErrorCause());
			responses.add(to);
			return responses;
		}
		
		if (!request.isThisMyPublicKey()) {
			LoggerResponseTO loggerResponseTO = new LoggerResponseTO();
			loggerResponseTO.setMessage(ControlMessages.getUnknownEntityTryingToResumeWorkerMessage(request.getSenderPublicKey()));
			loggerResponseTO.setType(LoggerResponseTO.WARN);

			responses.add(loggerResponseTO);
			return responses;
		}
		
		if (WorkerDAOFactory.getInstance().getWorkerStatusDAO().getStatus().equals(WorkerStatus.OWNER)) {
			responses.add(new LoggerResponseTO(ControlMessages.getOwnerWorkerResumedMessage(), LoggerResponseTO.INFO));
			responses.add(new LoggerResponseTO(ControlMessages.getWorkerStatusChangedMessage(WorkerStatus.OWNER, WorkerStatus.IDLE), 
					LoggerResponseTO.DEBUG));
			
			WorkerDAOFactory.getInstance().getWorkerStatusDAO().setStatus(WorkerStatus.IDLE);
			
			ExecutionController.getInstance().beginAllocation(responses);
		}
		
		OperationSucceedResponseTO operationSuccededResponseTO = new OperationSucceedResponseTO();
		operationSuccededResponseTO.setClientAddress(request.getClientAddress());
		responses.add(operationSuccededResponseTO);
		
		return responses;
	}
}
